package com.yng.simbot01.AiChat;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Component;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

@Component
public class QingYunKeChatImpl implements AiChatInter{
    @Override
    public String chat(String message) {

        String encodeMessage;
        try {
            encodeMessage = URLEncoder.encode(message, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            return "编码错误";
        }

        // 创建 HttpClient 实例
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            // 创建 GET 请求
            HttpGet request = new HttpGet("http://api.qingyunke.com/api.php?key=free&appid=0&msg=" + encodeMessage);

            // 执行请求并获取响应
            HttpResponse response = httpClient.execute(request);

            int statusCode = response.getStatusLine().getStatusCode();
            System.out.println("Response Code: " + statusCode);

            // 校验响应码
            if (statusCode == 200) { // 200表示成功
                // 获取响应体
                String responseBody = EntityUtils.toString(response.getEntity());
                JSONObject resultJson = JSONObject.parseObject(responseBody);
                String replyMessage = (String) resultJson.get("content");

                return processReplyMessage(replyMessage);
            } else {
                return "服务器异常";
            }
        } catch (Exception e) {
            return "出现异常" + e.getMessage();
        }

    }

    //处理Ai返回的字符串
    private String processReplyMessage(String input){
        String output = input;
        output = output.replaceAll("\\{br}", "\n");
        output = output.replaceAll("\\{([^}]*)\\}", "[暂不支持表情转义]");
        return output;
    }
}
